# mcp_calc_server.py
import logging
from fastmcp import FastMCP

# 配置日志记录
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("calculator_mcp_server")

class CalculatorServer:
    def __init__(self, host="0.0.0.0", port=25565):
        # 初始化FastMCP服务器实例
        self.mcp = FastMCP(name="calculator", instructions="这是一个AI计算器MCP服务器")
        self.host = host
        self.port = port
        
        # 注册工具函数
        self._register_tools()
    
    def _register_tools(self):
        # 加法工具（使用@self.mcp.tool装饰器标记为可远程调用）
        @self.mcp.tool(name="add", description="计算两个数的和")
        async def add(a: float, b: float) -> float:
            result = a + b
            logger.info(f"计算: {a} + {b} = {result}")
            return result
        
        # 乘法工具
        @self.mcp.tool(name="multiply", description="计算两个数的积")
        async def multiply(a: float, b: float) -> float:
            result = a * b
            logger.info(f"计算: {a} * {b} = {result}")
            return result
    
    def run(self):
        # 使用HTTP传输协议运行服务器
        print(f"服务器启动在 {self.host}:{self.port}")
        try:
            # 使用http传输并指定端口
            self.mcp.run(transport="http", host=self.host, port=self.port)
        except KeyboardInterrupt:
            print("\n服务器正在关闭...")

def main():
    server = CalculatorServer()
    # FastMCP的run()方法是同步的，直接调用
    server.run()

if __name__ == "__main__":
    # 直接调用main函数，因为它现在是同步的
    main()